using System.Collections.Generic;
using System.IO;

namespace ByteFarm.ImageMetaData.Format.Tiff
{
    public class TiffInfoProvider
    {
        public ICollection<ImageFileDirectory<Tag, FieldType>> GetInfo(string path)
        {
            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                using (BinaryReader binaryReader = new BinaryReader(fs))
                {
                    char[] chars = binaryReader.ReadChars(2);

                    ByteOrder byteOrder = chars[0] == 'M' ? ByteOrder.BigEndian : ByteOrder.LittleEndian;
                    TiffReader tiffReader = new TiffReader(byteOrder, binaryReader);

                    int num = tiffReader.ReadUInt16();
                    int offset = tiffReader.ReadUInt16();


                    ImageFileDirectoryFactory<Tag, FieldType> factory =
                        new ImageFileDirectoryFactory<Tag, FieldType>(new TiffDirectoryEntryFactory(tiffReader));

                    int nextOffset = offset;
                    List<ImageFileDirectory<Tag, FieldType>> imageFileDirectories =
                        new List<ImageFileDirectory<Tag, FieldType>>();
                    while (nextOffset != 0)
                    {
                        fs.Seek(nextOffset, SeekOrigin.Begin);
                        imageFileDirectories.Add(factory.CreateImageFileDirectory(out nextOffset));
                    }

                    return imageFileDirectories;
                }
            }
        }
    }
}